package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"
)

/*
Usage1: go run removePlugin.go panel.demo,datasource.demo

# This will remove panel plugin demo and also remove datasource plugin demo

Usage2: go run removePlugin.go all

This will remove all external plugins
*/
func main() {
	args := os.Args
	if len(args) != 2 {
		log.Println("Usage: go run removePlugins.go [panel|datasource].[pluginType]  e.g. go run removePlugin.go panel.demo,datasource.demo , this will remove panel plugin demo and also remove datasource plugin demo")
		return
	}

	if args[1] == "all" {
		externalPluginFile := `
// DON'T modify this file, it is automatically generated by Datav external plugin system
import { DatasourcePluginComponents, PanelPluginComponents } from "types/plugin"

export const externalPanelPlugins: Record<string,PanelPluginComponents> = {
}

export const externalDatasourcePlugins: Record<string,DatasourcePluginComponents> = {
}
`

		err := os.WriteFile("../frontend/src/views/dashboard/plugins/external/plugins.ts", []byte(externalPluginFile), 0666)
		if err != nil {
			log.Fatal("write plugins.ts error", err)
		}

		cmd := exec.Command("bash", "-c", "rm -rf ../frontend/src/views/dashboard/plugins/external/*/*")
		cmd.CombinedOutput()

		cmd = exec.Command("bash", "-c", "rm -rf ../query/internal/plugins/external/*")
		cmd.CombinedOutput()
	} else {
		removeList := strings.Split(args[1], ",")

		for _, plugin := range removeList {
			p := strings.Split(plugin, ".")
			if len(p) != 2 {
				log.Println("Plugin to be remmoved must be [panel|datasource].[pluginType]  e.g. panel.demo,datasource.demo")
				return
			}

			tp := p[0]
			if tp != "panel" && tp != "datasource" && tp != "query" {
				log.Println(tp + "is not a valid plugin type, plugin type only support panel, datasource or query,  Usage: e.g. go run removePlugin.go panel.demo,datasource.demo , this will remove panel plugin demo and also remove datasource plugin demo")
				return
			}

			pluginType := p[1]

			if tp == "query" {
				cmd := exec.Command("bash", "-c", fmt.Sprintf("rm -rf ../query/internal/plugins/external/%s", pluginType))
				cmd.CombinedOutput()
				continue
			} else {
				// remove plugin code
				cmd1 := exec.Command("bash", "-c", fmt.Sprintf("rm -rf ../frontend/src/views/dashboard/plugins/external/%s/%s", tp, pluginType))
				cmd1.CombinedOutput()
			}
		}

		// rebuild the plugins
		cmd := exec.Command("bash", "-c", fmt.Sprintf("go run buildPlugins.go -skip %s", args[1]))
		cmd.CombinedOutput()
	}

	log.Println("Remove plugins successfully!")
}
